﻿/**
* Created by kj on 2018/1/30.
*/
var viewer, scene, canvas, ellipsoid, camera, tileset, handler;


var oDate = new Date();
var sYear = oDate.getFullYear();
var sMonth = oDate.getMonth() + 1;
var sMonth = sMonth < 10 ? "0" + sMonth : sMonth;
var sDate = oDate.getDate();
sDate = sDate < 10 ? "0" + sDate : sDate;

document.getElementById("systime").innerHTML = sYear + "年" + sMonth + "月" + sDate + "日";

function disabledDantihua(bShow) {
    var groundArr = attachPolygonDataSource._visualizers;
    for (var i = 0; i < groundArr.length; i++) {
        if (groundArr[i]._groundColorBatch) {
            groundArr[i]._groundColorBatch._primitives.show = bShow;
        }
    }
}

$(function () {
    //头部属性设置
    $("#smallfunc").on("click", ".earth-check", function () {
        var wgArr = attachPolygonDataSource._entityCollection._entities._array;
        var oCheck = $(this);
        var bShow;
        if ($(this).hasClass("active")) {
            //TODO
            oCheck.removeClass("active");
            bShow = false;
        } else {
            //TODO
            oCheck.addClass("active");
            bShow = true;
        }
        if (oCheck.attr("data-func") == 3) {
            disabledDantihua(bShow);
        } else if (oCheck.attr("data-func") == 2) {
            for (var i = 0; i < wgArr.length; i++) {
                wgArr[i]._show = bShow;
            }
        } else if (oCheck.attr("data-func") == 1) {
            //fnObjShowHide([oRoadDatasource, oRoadDatasource1], "all", bShow);

        }
    });
    //一级菜单
    $("#work-menu .work-menu-item").click(function () {
        var oMenuItem = $(this);
        if (oMenuItem.hasClass("active")) {
            oMenuItem.removeClass("active");
            $(".work-menu-sub-item[data-menu=" + oMenuItem.attr("data-menu") + "]").addClass("hidden");
        } else {
            oMenuItem.addClass("active").siblings().removeClass("active");
            $(".work-menu-sub-item[data-menu=" + oMenuItem.attr("data-menu") + "]").removeClass("hidden").siblings().addClass("hidden");
        }
    });

    /*菜单滚动*/
    $(".work-submenu-content,.search-drop").mCustomScrollbar();
    $(window).resize(function () {
        $(".work-submenu-content,.search-drop").mCustomScrollbar("update");

    });
    //$(".search-drop").mCustomScrollbar();

    //收起二级菜单
    $(".work-submenu-title .arrow").click(function () {
        $(this).parents(".work-menu-sub-item").addClass("hidden");
        $("#work-menu .work-menu-item").removeClass("active");
    });

    //三级菜单收缩(标题) 网格列表飞行
    $("#personMenuContent,#houseMenuContent,#eventsMenuContent,#monitorMenuContent,#gridsMenuContent,#hujiMenuContent").on("click", ".work-child-title", function () {
        var oCheck = $(this);
        var oParents = oCheck.parents(".work-submenu-child");
        if (oParents.hasClass("active")) {
            //TODO
            oParents.removeClass("active");
        } else {
            //TODO
            oParents.addClass("active");
        }
        if (oCheck.parents(".work-submenu-content").hasClass("grids")) {
            oParents.addClass("active").siblings().removeClass("active");

            //获取单体化对象
            var oEntity = attachPolygonDataSource.entities.getById($(this).parent().attr("data-id"));
            var oDegree = getRealPosition(oEntity);
            console.log(oDegree);
            var oPos = {
                destination: LSGlobe.Cartesian3.fromDegrees(oDegree.lng, oDegree.lat, oDegree.alt),
                duration: 1
            };
            viewer.camera.flyTo(oPos);
        }
        return false;
    });
    //三级菜单收缩(标题)
    $("#personMenuContent,#houseMenuContent,#eventsMenuContent,#monitorMenuContent,#gridsMenuContent,#hujiMenuContent").on("click", ".arrow", function () {
        var oCheck = $(this);
        var oParents = oCheck.parents(".work-submenu-child");
        if (oParents.hasClass("active")) {
            //TODO
            oParents.removeClass("active");
        } else {
            //TODO
            oParents.addClass("active");
        }
        return false;
    });


    //三级菜单显隐
    $("#personMenuContent,#monitorMenuContent,#houseMenuContent,#hujiMenuContent").on("click", ".check", function () {
        var oCheck = $(this);
        var oParents = oCheck.parents(".work-submenu-content");
        var allCheckControl = $(this).parent().parent().parent().parent().parent().parent().parent().find(".allCheck");

        if ($(this).hasClass("active")) {
            //隐藏
            oCheck.removeClass("active");

            oCheck.parent().next().addClass("isHide");
            oCheck.parent().next().find(".work-child-item").attr("title", "请先勾选地图显示，再查看具体信息");
            allCheckControl.removeClass("active");
            oCheck.parent().next().find(".work-child-item").each(function () {
                var dataId = $(this).attr("data-id");
                mark.showMark(dataId, false);
            });
        } else {
            //显示
            oCheck.addClass("active");

            oCheck.parent().next().removeClass("isHide");
            oCheck.parent().next().find(".work-child-item").attr("title", "");
            oCheck.parent().next().find(".work-child-item").each(function () {
                var dataId = $(this).attr("data-id");
                mark.showMark(dataId, true);
            });

            if (oParents.find(".check.active").length == oParents.find(".check").length) {
                allCheckControl.addClass("active");
            }
        }

        return false;
    });


    //客服信息窗口滚动
    $("#message-box").mCustomScrollbar();
    var layerIndex = "0";
    //弹出客服
    $("#xiaoV-Btn").click(function () {
        if (layerIndex == "0") {
            layer.config({
                extend: 'myskin/style.css',
                skin: "xiaoV-popover"
            });
            layerIndex = layer.open({
                id: "xiao-v-close",
                type: 1, //Page层类型
                title: "智能小V，竭诚为您服务",
                shade: 0, //遮罩透明度
                area: '550px',
                anim: -1, //0-6的动画形式，-1不开启
                offset: ['calc(100% - 435px)', 'calc(100% - 680px)'],
                cancel: function () {
                    layerIndex = "0";
                },
                content: $("#xiaoV-manage")
            });
        } else {
            layer.close(layerIndex);
            layerIndex = "0";
        }

    });
    //发送信息
    $("#send-V-message").on("keyup", function (e) {
        if (e.keyCode == "13") {
            var oThis = $(this);
            if ($.trim(oThis.val()) != "") {
                $("#sub-V-message").trigger("click");
            }
        }
    });
    //点击btn发送信息
    $("#sub-V-message").on("click", function () {
        var messageTextarea = $("#send-V-message");
        var oValue = messageTextarea.val();
        var oMessageBox = $(".message-box");
        var sendHtml = "";
        sendHtml += "<div class=\"message-item right\">";
        sendHtml += "     <i class=\"head\"></i>";
        sendHtml += "     <div class=\"message-info\">" + oValue + "</div>";
        sendHtml += "</div>";
        oMessageBox.append(sendHtml);
        messageTextarea.val("");
        setTimeout(function () {
            var loadHtml = "";
            loadHtml += "<div class=\"message-item\">";
            loadHtml += "   <i class=\"manage\"></i>";
            loadHtml += "   <div class=\"message-info problem\">";
            loadHtml += "      <p>请点击您想查询的问题：</p>";
            loadHtml += "      <p class=\"blue\">1、人员小于50的网格</p>";
            loadHtml += "      <p class=\"blue\">2、小于20岁的重点青少年</p>";
            loadHtml += "      <p class=\"blue\">3、坏掉摄像头有哪些</p>";
            loadHtml += "      <p class=\"blue\">4、待处理事件有哪些</p>";
            loadHtml += "   </div>";
            loadHtml += "</div>";
            oMessageBox.append(loadHtml);
            var ScrollTop = 236 - oMessageBox.height() - 30;
            var oMessageId = $("#message-box");
            oMessageId.find(".mCSB_container").animate({ "top": ScrollTop + "px" }, 200);
            var oHeightBtn = oMessageId.height();
            var btnScrollTop = Math.round((oHeightBtn - (Math.round((Math.pow(oHeightBtn, 2) / oMessageBox.height())))));
            oMessageId.find(".mCSB_dragger").animate({ "top": btnScrollTop + "px" }, 200);
        }, 500);
    });
    $(".message-box").on("click", ".message-info.problem p.blue", function () {
        var oThis = $(this);
        var oIndex = oThis.index();
        smartSearch(oIndex);
    });
    //关闭
    $(document).on("click", ".layui-layer-close", function () {
        var oThis = $(this);
        var oSiblings = oThis.parent().prev().attr("id");
        if (oSiblings == "xiao-v-close") {
            //左侧回到原状
            for (var a = 0; a < aXiaoVSearch.length; a++) {
                aXiaoVSearch[a].show = aXiaoVSearch[a].originShow;
                aXiaoVSearch[a].searchShow = false;
            }
            aXiaoVSearch = [];
        }
    });


    //问题飞行
    $(".message-box").on("click", ".message-info.message  p.blue", function () {
        var oThis = $(this);
        var oType = oThis.parent().attr("data-type");
        var oId = oThis.attr("id");
        var oEntity = "";
        if (oType == "grid") {
            oEntity = oGridDataSource.entities.getById(oId);
        } else if (oType == "people") {
            oEntity = oPeopleDatasource["zhongdianqingshaonian"].entities.getById(oId);
        } else if (oType == "monitor") {
            oEntity = monitorGeojson.entities.getById(oId);
            var oTargetEntity = viewer.entities.getById(oId);
            oTargetEntity.show = true;
            aXiaoVSearch.push(oTargetEntity);
        } else if (oType == "event") {
            oEntity = eventGeojson.entities.getById(oId);
            var oTargetEntity = viewer.entities.getById(oId);
            oTargetEntity.show = true;
            aXiaoVSearch.push(oTargetEntity);
        }
        oEntity.show = true;
        aXiaoVSearch.push(oEntity);

        if (oType == "grid") {
            var oDegree = getRealPosition(oEntity);
            var oPos = {
                destination: LSGlobe.Cartesian3.fromDegrees(oDegree.lng, oDegree.lat, oDegree.alt),
                duration: 1
            };
            viewer.camera.flyTo(oPos);
        } else {
            viewer.flyTo(oEntity);
        }
    });
});


//获取真实位置
function getRealPosition(Entities) {

    var aPos = Entities.polygon.hierarchy._value.positions;

    var iX = 0, iY = 0, iZ = 0, maxX = 0, maxY = 0, minX, minY, realheight;
    for (var i = 0; i < aPos.length; i++) {
        iX = aPos[i].x + iX;
        iY = aPos[i].y + iY;
        iZ = aPos[i].z + iZ;
    }
    iX = iX / aPos.length;
    iY = iY / aPos.length;
    iZ = iZ / aPos.length;

    //中心点经纬度
    var WorlsPos = new LSGlobe.Cartesian3(iX, iY, iZ);
    var oDegree = ellipsoid.cartesianToCartographic(WorlsPos);
    var lng = LSGlobe.Math.toDegrees(oDegree.longitude);
    var lat = LSGlobe.Math.toDegrees(oDegree.latitude);

    //遍历面所有点
    for (var a = 0; a < aPos.length; a++) {
        //当前点的经纬度
        var sWorlsPos = new LSGlobe.Cartesian3(aPos[a].x, aPos[a].y, aPos[a].z);
        var sDegree = ellipsoid.cartesianToCartographic(sWorlsPos);
        var slng = LSGlobe.Math.toDegrees(sDegree.longitude);
        var slat = LSGlobe.Math.toDegrees(sDegree.latitude);

        //当前点对象
        var oPos = { "x": slng, "y": slat };
        //到中心点距离

        var currentheight = getDistance(oPos, lng, lat);
        if (a == 0) {
            realheight = currentheight
        }
        //取到中心点最大距离点
        if (realheight < currentheight) {
            realheight = currentheight
        }
    }
    var sTileset = whichTileset(lng, lat);
    var alt = realheight * 1.7320508075689 + 50 + sTileset._boundingSphere.center.z * 1 + sTileset._position.z * 1;
    return { "lat": lat, "lng": lng, "alt": alt };
}

function whichTileset(x, y) {
    var returnValue = "";
    for (var i = 0; i < viewer.scene.primitives.length; i++) {
        var aTileSet = viewer.scene.primitives.get(i);
        if (aTileSet._type == "pageLOD") {
            var oCenter = aTileSet.tileBoundingSphere.center;
            var ellipsoid = viewer.scene.globe.ellipsoid;
            var cartesian3 = new LSGlobe.Cartesian3(oCenter.x, oCenter.y, oCenter.z);
            var cartographic = ellipsoid.cartesianToCartographic(cartesian3);
            var lat = LSGlobe.Math.toDegrees(cartographic.latitude);
            var lng = LSGlobe.Math.toDegrees(cartographic.longitude);
            var position = { x: lng, y: lat, z: cartographic.height };

            var distance = getDistance(position, x, y);
            if (distance < aTileSet.tileBoundingSphere.radius) {
                returnValue = aTileSet;
            }
        }
    }
    return returnValue;
}

//距离
function getDistance(position, x, y) {
    var radLatA = position.y * 0.0174532925199432957692369077;
    var radLatB = y * 0.0174532925199432957692369077;
    var radLonA = position.x * 0.0174532925199432957692369077;
    var radLonB = x * 0.0174532925199432957692369077;
    return Math.acos(
            Math.cos(radLatA) * Math.cos(radLatB) * Math.cos(radLonA - radLonB) +
            Math.sin(radLatA) * Math.sin(radLatB)) * 6378137;
}

function fnObjShowHide(obj, type, bshow) {
    /*obj:对象
    type:属性类型
    bshow:是否显示 true:显示 false:y隐藏*/
    if ("all" == type) {
        for (var i = 0; i < obj.length; i++) {
            obj[i].originShow = bshow;
            if (!bshow && obj[i].searchShow) {
                //如果是隐藏操作且当前处于搜索锁定状态
                continue;
            }
            obj[i].show = bshow;
        }
    } else {
        var entities = obj.entities.values;
        for (var i = 0; i < entities.length; i++) {
            var entity = entities[i];
            if (!!entity[type]) {
                entity.originShow = bshow;
                if (!bshow && entity.searchShow) {
                    //如果是隐藏操作且当前处于搜索锁定状态
                    continue;
                }
                entity.show = bshow;
            } else if ("marker" == type) {
                if (!!entity.billboard || !!entity.label) {
                    entity.originShow = bshow;
                    if (!bshow && entity.searchShow) {
                        //如果是隐藏操作且当前处于搜索锁定状态
                        continue;
                    }
                    entity.show = bshow;
                }
            }
        }
    }
}
